-- Complex operator that will require explicit locking.
-- ==
-- input {
-- 10i64
-- [0.0f32, 1.0f32, 2.0f32, 3.0f32, 4.0f32, 5.0f32, 6.0f32, 7.0f32, 8.0f32, 9.0f32, 10.0f32, 11.0f32, 12.0f32, 13.0f32, 14.0f32, 15.0f32, 16.0f32, 17.0f32, 18.0f32, 19.0f32, 20.0f32, 21.0f32, 22.0f32, 23.0f32, 24.0f32, 25.0f32, 26.0f32, 27.0f32, 28.0f32, 29.0f32, 30.0f32, 31.0f32, 32.0f32, 33.0f32, 34.0f32, 35.0f32, 36.0f32, 37.0f32, 38.0f32, 39.0f32, 40.0f32, 41.0f32, 42.0f32, 43.0f32, 44.0f32, 45.0f32, 46.0f32, 47.0f32, 48.0f32, 49.0f32, 50.0f32, 51.0f32, 52.0f32, 53.0f32, 54.0f32, 55.0f32, 56.0f32, 57.0f32, 58.0f32, 59.0f32, 60.0f32, 61.0f32, 62.0f32, 63.0f32, 64.0f32, 65.0f32, 66.0f32, 67.0f32, 68.0f32, 69.0f32, 70.0f32, 71.0f32, 72.0f32, 73.0f32, 74.0f32, 75.0f32, 76.0f32, 77.0f32, 78.0f32, 79.0f32, 80.0f32, 81.0f32, 82.0f32, 83.0f32, 84.0f32, 85.0f32, 86.0f32, 87.0f32, 88.0f32, 89.0f32, 90.0f32, 91.0f32, 92.0f32, 93.0f32, 94.0f32, 95.0f32, 96.0f32, 97.0f32, 98.0f32, 99.0f32]
-- }
-- output {
-- [90.0f32, 91.0f32, 92.0f32, 93.0f32, 94.0f32, 95.0f32, 96.0f32, 97.0f32, 98.0f32, 99.0f32]
-- [90i64, 91i64, 92i64, 93i64, 94i64, 95i64, 96i64, 97i64, 98i64, 99i64]
-- }

import "intrinsics"

def f n (acc: *acc ([](f32, i64))) (i, x) =
  write acc (i % n) (x, i)

def main n (xs: []f32) =
  let op =
    (\(a, i) (b, j) ->
       if a < b
       then (b, j)
       else if b < a
       then (a, i)
       else if j < i
       then (b, j)
       else (a, i))
  in reduce_by_index_stream (replicate n (0, 0))
                            op
                            (f32.lowest, -1)
                            (f n)
                            (zip (indices xs) xs)
     |> unzip
